<template>
    <div class="box">
        <vab-card id="fixedCard" class="fixedName" :class="{ 'collapse': useSettingsStore().collapse }">
            <template #default>
                <div class="flex_sb">
                    <div class="flex">
                        <div class="flex leve_title">
                            折扣赠品设置
                            <span v-if="isShowUid"> -{{ route.query.id }}</span>
                        </div>
                        <span>策略状态-{{ ReturnnStatus(`${route.query.status}`, 'label') }}</span>
                    </div>
                    <div class="flex_just_end">
                        <VabButton update v-if="isShowSave" title="暂存" @click="_customerPriceCreate(0)" />
                        <VabButton title="取消" @click="handleClick('back')" />
                        <VabButton type="primary" title="提交" @click="_customerPriceCreate(1)" />
                    </div>
                </div>
            </template>
        </vab-card>
  
        <div v-loading="createLoading">
            <!-- 基础信息-使用范围 -->
            <CreateInfo ref="createInfoRef" id="createInfoEl" @useOrgSelect="useOrgSelect"/>
            <!-- 规则详情-折扣项 -->
            <!-- <RuleDateilMode ref="ruleDateilModeRef" /> -->
            <!-- 规则详情-指定产品[满金额]赠 -->
            <ProductMoney ref="productMoneyRef" id="productMoneyEl" :useOrgId="useOrgId"/>
            <!-- 适用范围 -->
            <SuitRange ref="suitRangeRef" id="suitRangeEl"/>
        </div>
    </div>
  </template>
  
<script setup lang="ts">

defineOptions({
    name: 'GiveawayCreate'
})

/**
* @import
*/

import { DateFormat, IsValueHave } from '~/src/utils/utils';
import { orderDiscountInfo, orderDiscountUpdate, orderDiscountInsert } from '~/src/api/dms/order';
import { ReturnnStatus } from './component/tools';
import { useSettingsStore } from '~/src/store/modules/settings'

import CreateInfo from './component/CreateInfo.vue'
import ProductMoney from './component/ProductMoney.vue'
import SuitRange from './component/SuitRange.vue'

/**
* @var
*/
const proxy: any = getCurrentInstance()?.proxy
const router = useRouter()
const route = useRoute()


let fromPage = ref<any>('')
let fromID = ref<any>(null)
let fromStatus = ref('')


const createInfoRef = ref()
const productMoneyRef = ref()
const suitRangeRef = ref()

let useOrgId = ref<string>('')
let createLoading = ref<any>(false)

/**
* @method
*/

//  点击事件
const handleClick = async (value: any) => {
    if (value == 'back') {
        router.go(-1)
        return
    }
}
// 滚动指定位置
const handleScrollInto = (el: any) => {
    document
        .getElementById(el)
        ?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
// 切换使用组织
const useOrgSelect = (value: string, lay = false) => {
    productMoneyRef.value.handleUseOrgId({ value, lay })
    suitRangeRef.value.handleUseOrgId({ value, lay })
}

// 创建
const _customerPriceCreate = async (status: number) => {
    // 基本信息 校验
    const baseValidate = await createInfoRef.value.baseFormRef.validate((valid: any) => {
        if (valid) return true
        return false
    })

    if (!baseValidate) {
        handleScrollInto('createInfoEl')
        return
    }
    const baseForm: any = createInfoRef.value.baseForm
    const { number, name, type, is_enable, level, effective_date, use_org_id } = baseForm

    //规则详情校驗
    let ruleForm: any = productMoneyRef.value.ruleForm

    let productValidate = false
    let giftValidate = false

    for (let i = 0; i < ruleForm.length; i++) {

        const productList = [...ruleForm[i].product]
        const giftList = [...ruleForm[i].gift]

        productValidate = productList.some((item: any) => {
            return !item.goods_no || !item.goods_barcode || !item.goods_name || !IsValueHave(item.goods_num)
        })

        giftValidate = giftList.some((item: any) => {
            return !item.goods_no || !item.goods_barcode || !item.goods_name ||
                !IsValueHave(item.goods_num) || !IsValueHave(item.is_require)
        })

        if (productValidate) break
        if (giftValidate) break
    }

    if (productValidate || giftValidate) {
        proxy.$Message('请正确填写规则详情信息!', 'warning')
        handleScrollInto('productMoneyEl')
        return
    }

    // 使用范围 校验
    let VoidJudgment = false
    const customerList: never[] = suitRangeRef.value.customerList.map((item: any) => {
        return {
            is_default: item.is_default,
            customer_uid: item.customer_uid,
            customer_name: item.customer_name,
            customer_number: item.customer_number,
        }
    })
    if (customerList.length) {
        VoidJudgment = customerList.some((item: any) => { return !item.customer_uid || !item.is_default })
        if (VoidJudgment) {
            proxy.$Message('请正确填写使用范围信息!', 'warning')
            handleScrollInto('suitRangeEl')
            return
        }
    }

    let data: any = {
        info: {
            // number,
            name,
            type,
            is_enable,
            // level,
            status,
            use_org_id,
            effective_start: effective_date ? DateFormat(effective_date[0]) : '',
            effective_end: effective_date ? DateFormat(effective_date[1]) : '',
        },
        customer_list: customerList || [], //产品列表
        item_list: ruleForm, //规则列表
    }

    if (route.query.from == 'copy') baseForm.uid = ''

    const { uid } = baseForm

    // 通过有无id判断 
    if (uid) {
        data.uid = uid
        orderDiscountUpdate({ ...data }).then((res: any) => {
            proxy.$Message(`${status == 1 ? '提交' : '暂存'}成功`, 'success')
            router.go(-1)
        }).catch(err => {
        })
    } else {
        orderDiscountInsert({ ...data }).then((res: any) => {
            proxy.$Message(`${status == 1 ? '提交' : '暂存'}成功`, 'success')
            router.go(-1)
        }).catch(err => {

        })
    }
}

// 获取更新数据
const _GetUpdateInfo = async () => {
    try {
        const res = await orderDiscountInfo({ uid: fromID.value })
        createInfoRef.value.getUpdateData(res.data)
        productMoneyRef.value.getUpdateData(res.data)
        suitRangeRef.value.getUpdateData(res.data)
    } catch (error) { }
}

// 重置数据
const _GetResetInfo = async () => {
    createInfoRef.value.getResetData()
    productMoneyRef.value.getResetData()
    suitRangeRef.value.getResetData()
}
/**
* @实例
*/

const isShowSave = computed(() => {
    if (fromStatus.value == undefined) return true
    if (Number(fromStatus.value) < 1) return true
    return false
})
const isShowUid = computed(() => {
    if (route.query.from == 'copy' ||
        route.query.from == 'create'
    ) return false
    return true
})



onActivated(async () => {
    // 页面参数赋值
    const { from, handleStatus, id } = route.query

    // 创建单留存【第二次打开，判断路径id是否相同，相同不执行，不同继续执行】
    if (fromID.value === id) return

    createLoading.value = true

    fromPage.value = from
    fromID.value = id
    fromStatus.value = handleStatus

    fromPage.value = from == 'toHandle' ? 'copy' : from
    if (fromPage.value != 'create') {
        await _GetUpdateInfo()
    } else {
        await _GetResetInfo()
    }

    createLoading.value = false
})

</script>
  
<style scoped>
.box {
    padding-top: 50px;
}
</style>